package com.ruoyi.gbase.task;

import com.ruoyi.gbase.util.ExecuteShellUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;


/**
 * 省联社准实时数据同步调度
 * 
 * @author ruoyi
 */
@Component("realDataSyn")
public class RealDataSynchronizTask
{
    private static final Logger log = LoggerFactory.getLogger(RealDataSynchronizTask.class);

    @Value("${tdcClient.ip}")
    private  String ip;

    @Value("${tdcClient.port}")
    private  int port;

    @Value("${tdcClient.username}")
    private  String username;

    @Value("${tdcClient.pwd}")
    private  String pwd;

    /**
     * 自动任务_执行sql 同步数据库
     * tablename: s_cbod_cboddbpd_saacntxn
     * whereStr:  where sa_tx_dt=from_unixtime[unix_timestamp[],$yyyyMMdd$]
     * 注意  需要替换 [] $ ;  因为内置的不带 ()和' ,
     * sh /home/TDC-Client/hadoop2file/bin/hadoop2gbase.sh "all" "select * from rds.s_cbod_cboddbpd_saacntxn
     *  where sa_tx_dt=from_unixtime(unix_timestamp(), 'yyyyMMdd')" "s_cbod_cboddbpd_saacntxn.txt"
     */
    public void synData(String tablename,String whereStr)
    {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            if("32.202.51.181-2".equals(addr.getHostAddress())){
                log.info("当前为本机运行，不做实时同步操作！！！ IP:"+addr.getHostAddress());
                //return ;
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        log.info(tablename+"同步开始");
        try {
            ExecuteShellUtil sshClient = ExecuteShellUtil.getInstance();
            sshClient.init(ip,port, username, pwd);
            String shStr = "sh /home/TDC-Client/hadoop2file/bin/hadoop2gbase.sh \"all\" \"select * from rds."+tablename.toLowerCase()
                    +" "+whereStr.replace("$","'").replace("[","(").replace("]",")")
                        .replace(";",",")
                    +"\" \""+tablename+".txt\"";
            log.info("执行的shell命令是 ："+shStr);

            sshClient.execCmd(shStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info(tablename+"同步结束");
    }


}
